using System;
using System.Collections.Generic;
using AI.Graph;
using UnityEngine;

[CreateNodeMenu ("Condition/Can See")]
public class CanSeeCondition : Condition {

    [ParameterType (typeof (FieldOfView))]
    public ExposedParameter fieldOfViewParameter;

    [ParameterType (typeof (GameObject))]
    public NodeParameter visibleTargetParameter;

    [ParameterType (typeof (GameObject[]))]
    public NodeParameter visibleTargetsParameter;

    [Range (0, 360)]
    public float viewAngle = 60;

    public float viewRadius = 10;
    public LayerMask targetMask;
    public LayerMask obstacleMask;

    private FieldOfView fov;

    [NonSerialized]
    public List<GameObject> visibleTargetsList = new List<GameObject> ();


    protected override void OnStart (AIBehaviour aiBehaviour) {
        if (!aiBehaviour.TryGetExposedObject (fieldOfViewParameter, out fov)) {
            Debug.LogWarning ("The Can See Condition has no Field Of View.");
        }
    }


    protected override bool OnDecide (AIBehaviour aiBehaviour) {
        if (fov != null) {
            fov.targetMask = targetMask;
            fov.obstacleMask = obstacleMask;
            fov.viewAngle = viewAngle;
            fov.viewRadius = viewRadius;
            fov.FindVisibleTargets (ref visibleTargetsList);

            if (visibleTargetsList.Count > 0) {
                bool flag1 = false;
                bool flag2 = false;

                if (visibleTargetParameter != null) {
                    flag1 = aiBehaviour.TrySetValue (visibleTargetParameter, visibleTargetsList.ToArray ()[0]);
                }

                if (visibleTargetsParameter != null) {
                    flag2 = aiBehaviour.TrySetValue (visibleTargetsParameter, visibleTargetsList.ToArray ());
                }

                return flag1 || flag2;
            }
        }

        return false;
    }

}